﻿
using Core.Module;
using Core.Module.Interfaces.Model;
using Module.SiteWidgets.Interfaces;
using System.Web.UI.WebControls;
using umbraco.BusinessLogic;
using System;
using System.Web.UI;
using umbraco.presentation;
using ClientDependency.Core;

namespace Module.SiteWidgets.Controls
{
    [ClientDependency(ClientDependencyType.Css, "~/css/widgets.css")] 
    public class WidgetsRenderer : WebControl
    {
        public string SourceFieldName { get; set; }

        public int SourcePageId; 
        public IModuleNode _SourcePage;
        public IModuleNode SourcePage{ get {
            if (_SourcePage == null)
            {
                if (SourcePageId == 0) SourcePageId = UmbracoContext.Current.PageId ?? -1;
                _SourcePage = Core.Module.Context.Frontend.Nodes.Get(SourcePageId.ToString());
            } return _SourcePage;
        } set { _SourcePage = value; } }
        private ISiteWidjetsModule _WidgetsModule;
        public ISiteWidjetsModule WidgetsModule
        {
            get
            {
                if (_WidgetsModule == null)
                {
                    ISite pageSite =Core.Module.Context.Frontend.Sites.Get(SourcePage.SiteId);
                    if (pageSite == null) return LogErrorAndReturn<ISiteWidjetsModule>("can't return SiteWidjets module, can't determinate site for page:" + SourcePage.Url, LogTypes.Error, null);
                    ISiteWidjetsModule result = Core.Module.Context.Frontend.Modules.Get(pageSite, "SiteWidgetsModule") as ISiteWidjetsModule;
                    if (result == null) return LogErrorAndReturn<ISiteWidjetsModule>("No one module is installed and active for site:" + pageSite.Node.Name + " which can be used to render widgets [alias:SiteWidjetsModule]", LogTypes.Notify, null);
                    _WidgetsModule=result;
                }
                return _WidgetsModule;
            }
            set { _WidgetsModule = value; }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            foreach (Control witem in WidgetsModule.GetPageWidgets(SourcePage,SourceFieldName))
                this.Controls.Add(witem);
        }

        public override void RenderBeginTag(System.Web.UI.HtmlTextWriter writer)
        {
        }

        public override void RenderEndTag(System.Web.UI.HtmlTextWriter writer)
        {
        }
        private T LogErrorAndReturn<T>(string message, LogTypes ltype, T result)
        {
            Log.Add(ltype, -1, message);
            return result;
        }

    }
}
